const express = require('express')
const router = express.Router()
const db = require('../config/database')

/**
 * 获取章节详情
 * GET /api/chapters/:id
 */
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params

    const query = `
      SELECT c.*, n.title as novel_title, n.author
      FROM chapters c
      LEFT JOIN novels n ON c.novel_id = n.id
      WHERE c.id = ?
    `

    const chapters = await db.query(query, [id])

    if (chapters.length === 0) {
      return res.status(404).json({
        success: false,
        message: '章节不存在'
      })
    }

    const chapter = chapters[0]

    res.json({
      success: true,
      data: chapter
    })
  } catch (error) {
    console.error('获取章节详情失败:', error)
    res.status(500).json({
      success: false,
      message: '获取章节详情失败'
    })
  }
})

/**
 * 获取章节内容（需要权限检查）
 * GET /api/chapters/:id/content
 */
router.get('/:id/content', async (req, res) => {
  try {
    const { id } = req.params
    // const userId = req.user?.id; // 假设有用户认证中间件

    const query = `
      SELECT c.*, n.title as novel_title
      FROM chapters c
      LEFT JOIN novels n ON c.novel_id = n.id
      WHERE c.id = ?
    `

    const chapters = await db.query(query, [id])

    if (chapters.length === 0) {
      return res.status(404).json({
        success: false,
        message: '章节不存在'
      })
    }

    const chapter = chapters[0]

    // 检查是否为VIP章节
    if (chapter.is_vip && !chapter.is_free) {
      // TODO: 检查用户是否为VIP或已购买此章节
      // 这里暂时返回部分内容
      const preview = chapter.content
        ? chapter.content.substring(0, 200) + '...'
        : ''

      return res.json({
        success: true,
        data: {
          ...chapter,
          content: preview,
          isPreview: true,
          needsPurchase: true
        }
      })
    }

    res.json({
      success: true,
      data: {
        ...chapter,
        isPreview: false,
        needsPurchase: false
      }
    })
  } catch (error) {
    console.error('获取章节内容失败:', error)
    res.status(500).json({
      success: false,
      message: '获取章节内容失败'
    })
  }
})

module.exports = router
